package com.ncloud.crm.business;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.ncloud.aaaa.service.UserService;
import com.ncloud.chnl.service.CustUserService;
import com.ncloud.common.enmus.MessageBoxEnum;
import com.ncloud.crm.entity.Logistics;
import com.ncloud.crm.interFace.AcctFeeSyncInterface;
import com.ncloud.crm.service.*;
import com.ncloud.crm.utils.MsgBoxUtil;
import com.ncloud.msg.dubboservice.MailDubboService;
import com.ncloud.param.service.TagService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ncloud.common.enmus.ResultEnum;
import com.ncloud.common.exception.UserException;
import com.ncloud.crm.common.Constant;
import com.ncloud.crm.entity.order.Order;
import com.ncloud.crm.entity.order.OrderDiscnt;
import com.ncloud.crm.entity.order.OrderDiscntFee;
import com.ncloud.crm.entity.order.Work;
import com.ncloud.crm.service.impl.OrderFinishServiceImpl;
import com.ncloud.crm.utils.DateUtils;
import com.ncloud.crm.utils.OrderNodeDefineUtils;

/**
 * Created by shiqiang on 2017/4/13.
 */
@Service
public class OrderInfoBusi {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderCustomerService orderCustomerService;
    @Autowired
    private OrderAccountService orderAccountService;
    @Autowired
    private OrderProductService orderProductService;
    @Autowired
    private OrderAttrService orderAttrService;
    @Autowired
    private WorkService workService;
    @Autowired
    private WorkAttrService workAttrService;
    @Autowired
    private WorkNodeService workNodeService;
    @Autowired
    private WorkNodeNetAccessService workNodeInterService;
    @Autowired
    private WorkNodeEqptService workNodeEqptService;
    @Autowired
    private WorkNodeAttrService workNodeAttrService;
    @Autowired
    private WorkNodePublicCloudService workNodePublicCloudService;
    @Autowired
    private OrderFinishServiceImpl finishService;
    @Autowired
    private OrderDiscntService orderDiscntService;
    @Autowired
    private OrderContractService orderContractService;
    @Autowired
    private OrderDiscntFeeService orderDiscntFeeService;
    @Autowired
    private AcctFeeSyncInterface acctFeeSyncInterface;
    @Autowired
    private WorkNodePublicCloudSegService workNodePublicCloudSegService;
    @Autowired
    private LogisticsServer logisticsServer;
    @Autowired
    private MsgBoxServer msgBoxServer;
    @Reference
    private UserService userService;
    @Reference
    private MailDubboService mailService;
    @Reference
    private CustUserService custUserService;
    @Reference
    private TagService tagService;
    public JSONObject orderValidateInfo(JSONObject json,JSONObject json2){
        JSONObject orderInfos = new JSONObject();
        /*订单*/
        orderInfos.put(OrderNodeDefineUtils.ORDER,orderService.validate(json,json2));
        /*订单客户*/
        orderInfos.putAll(orderCustomerService.validate(json,json2));
        //orderInfos.put(OrderNodeDefineUtils.ORDER_CUSTOMER,orderCustomerService.validate(json,json2));
         /*订单账户*/
        orderInfos.put(OrderNodeDefineUtils.ORDER_ACCOUNT,orderAccountService.validate(json,json2));
         /*订单项目*/
        //orderInfos.put(OrderNodeDefineUtils.ORDER_PROJECT,orderProjectService.validate(json,json2));
        /*订单产品*/
        orderInfos.putAll(orderProductService.validate(json,json2));

        /*订单套餐*/
        orderInfos.putAll(orderDiscntService.validate(json,json2));
         /*订单套餐费用*/
       /* orderInfos.putAll(orderDiscntFeeService.validate(json,json2));*/
         /*订单合同*/
        orderInfos.putAll(orderContractService.validate(json,json2));
          /*工单*/
        //orderInfos.putAll(workService.validate(json,json2));
         /*订单节点*/
        orderInfos.putAll(workNodeService.validate(json,json2));
         /*工单节点设备*/
        //orderInfos.putAll(workNodeEqptService.validate(json,json2));
         /*工单节点ISp*/
        //orderInfos.putAll(workNodeInterService.validate(json,json2));
         /*工单属性*/
       // orderInfos.putAll(workAttrService.validate(json,json2));
          /*工单节点属性*/
        //orderInfos.putAll(workNodeAttrService.validate(json,json2));
          /*工单公有云信息*/
        //orderInfos.putAll(workNodePublicCloudService.validate(json,json2));

        /*------------------------接口数据-------------------------*/
        return orderInfos;
    }
    @Transactional
    public void orderInfoGene(JSONObject orderInfos){
        /*订单生成*/
        if(orderInfos.containsKey(OrderNodeDefineUtils.ORDER) && orderInfos.getJSONObject(OrderNodeDefineUtils.ORDER).size()>0){
            JSONObject order = orderInfos.getJSONObject(OrderNodeDefineUtils.ORDER);
            orderService.insertOrder(order);
        }
        /*订单属性生成*/
        if(orderInfos.containsKey(OrderNodeDefineUtils.ORDER_ITEM) && orderInfos.getJSONArray(OrderNodeDefineUtils.ORDER_ITEM).size()>0){
            JSONArray nodes = orderInfos.getJSONArray(OrderNodeDefineUtils.ORDER_ITEM);
            for(int i=0;i<nodes.size();i++){
                JSONObject node = nodes.getJSONObject(i);
                orderAttrService.insert(node);
            }
        }

        /*订单账户信息*/
        if(orderInfos.containsKey(OrderNodeDefineUtils.ORDER_ACCOUNT) && orderInfos.getJSONObject(OrderNodeDefineUtils.ORDER_ACCOUNT).size()>0){
            JSONObject order = orderInfos.getJSONObject(OrderNodeDefineUtils.ORDER_ACCOUNT);
            orderAccountService.insert(order);
        }
        /*订单项目信息*/
       /* if(orderInfos.containsKey(OrderNodeDefineUtils.ORDER_PROJECT) && orderInfos.getJSONObject(OrderNodeDefineUtils.ORDER_PROJECT).size()>0){
            JSONObject order = orderInfos.getJSONObject(OrderNodeDefineUtils.ORDER_PROJECT);
            orderProjectService.insert(order);
        }*/
        /*订单产品信息*/
        if(orderInfos.containsKey(OrderNodeDefineUtils.ORDER_PRODUCT) && orderInfos.getJSONArray(OrderNodeDefineUtils.ORDER_PRODUCT).size()>0){

            JSONArray nodes = orderInfos.getJSONArray(OrderNodeDefineUtils.ORDER_PRODUCT);
            for(int i=0;i<nodes.size();i++){
                JSONObject node = nodes.getJSONObject(i);
                orderProductService.insert(node);
            }
        }

        /*订单套餐信息*/
        if(orderInfos.containsKey(OrderNodeDefineUtils.ORDER_DISCNT) && orderInfos.getJSONArray(OrderNodeDefineUtils.ORDER_DISCNT).size()>0){
            JSONArray nodes = orderInfos.getJSONArray(OrderNodeDefineUtils.ORDER_DISCNT);
            for(int i=0;i<nodes.size();i++){
                JSONObject node = nodes.getJSONObject(i);
                orderDiscntService.insert(node);
            }
        }
        /*订单套餐费用信息*/
        if(orderInfos.containsKey(OrderNodeDefineUtils.ORDER_DISCNT_FEE) && orderInfos.getJSONArray(OrderNodeDefineUtils.ORDER_DISCNT_FEE).size()>0){
            JSONArray nodes = orderInfos.getJSONArray(OrderNodeDefineUtils.ORDER_DISCNT_FEE);
            for(int i=0;i<nodes.size();i++){
                JSONObject node = nodes.getJSONObject(i);
                orderDiscntFeeService.insert(node);
            }
        }
        /*订单合同信息*/
        if(orderInfos.containsKey(OrderNodeDefineUtils.ORDER_CONTRACT) && orderInfos.getJSONArray(OrderNodeDefineUtils.ORDER_CONTRACT).size()>0){
            JSONArray contracts = orderInfos.getJSONArray(OrderNodeDefineUtils.ORDER_CONTRACT);
            for(int i=0;i<contracts.size();i++){
                JSONObject contract = contracts.getJSONObject(i);
                orderContractService.insert(contract);
            }

        }
        /*施工单信息*/
        if(orderInfos.containsKey(OrderNodeDefineUtils.WORK) && orderInfos.getJSONArray(OrderNodeDefineUtils.WORK).size()>0){
            JSONArray works = orderInfos.getJSONArray(OrderNodeDefineUtils.WORK);
            for(int i=0;i<works.size();i++){
                JSONObject work = works.getJSONObject(i);
                workService.insert(work);
            }
        }
        /*施工单节点信息*/
        if(orderInfos.containsKey(OrderNodeDefineUtils.NODE) && orderInfos.getJSONArray(OrderNodeDefineUtils.NODE).size()>0){
            JSONArray nodes = orderInfos.getJSONArray(OrderNodeDefineUtils.NODE);
            for(int i=0;i<nodes.size();i++){
                JSONObject node = nodes.getJSONObject(i);
                workNodeService.insert(node);
            }
        }
        /*合同节点信息*/
       /* if(orderInfos.containsKey(OrderNodeDefineUtils.CONTRACT_NODE) && orderInfos.getJSONArray(OrderNodeDefineUtils.CONTRACT_NODE).size()>0){
            JSONArray nodes = orderInfos.getJSONArray(OrderNodeDefineUtils.CONTRACT_NODE);
            for(int i=0;i<nodes.size();i++){
                JSONObject node = nodes.getJSONObject(i);
                OrderContractNode contractNode = JSON.parseObject(node.toJSONString(),OrderContractNode.class);
                orderContractNodeService.insert(contractNode);
            }
        }*/
        /*施工单节点CPE信息*/
        if(orderInfos.containsKey(OrderNodeDefineUtils.NODE_EQPT) && orderInfos.getJSONArray(OrderNodeDefineUtils.NODE_EQPT).size()>0){
            JSONArray nodes = orderInfos.getJSONArray(OrderNodeDefineUtils.NODE_EQPT);
            for(int i=0;i<nodes.size();i++){
                JSONObject node = nodes.getJSONObject(i);
                workNodeEqptService.insert(node);
            }
        }
         /*施工单公有云信息*/
        if(orderInfos.containsKey(OrderNodeDefineUtils.NODE_PUBLIC_CLOUD) && orderInfos.getJSONArray(OrderNodeDefineUtils.NODE_PUBLIC_CLOUD).size()>0){
            JSONArray nodes = orderInfos.getJSONArray(OrderNodeDefineUtils.NODE_PUBLIC_CLOUD);
            for(int i=0;i<nodes.size();i++){
                JSONObject node = nodes.getJSONObject(i);
                workNodePublicCloudService.insert(node);
            }
        }
         /*施工单节点ISP信息*/
        if(orderInfos.containsKey(OrderNodeDefineUtils.NODE_INTER) && orderInfos.getJSONArray(OrderNodeDefineUtils.NODE_INTER).size()>0){
            JSONArray nodes = orderInfos.getJSONArray(OrderNodeDefineUtils.NODE_INTER);
            for(int i=0;i<nodes.size();i++){
                JSONObject node = nodes.getJSONObject(i);
                workNodeInterService.insert(node);
            }
        }
        /*施工单公有云网段信息*/
        if(orderInfos.containsKey(OrderNodeDefineUtils.PUBLIC_CLOUD_SEG) && orderInfos.getJSONArray(OrderNodeDefineUtils.PUBLIC_CLOUD_SEG).size()>0){
            JSONArray nodes = orderInfos.getJSONArray(OrderNodeDefineUtils.PUBLIC_CLOUD_SEG);
            for(int i=0;i<nodes.size();i++){
                JSONObject node = nodes.getJSONObject(i);
                workNodePublicCloudSegService.insert(node);
            }
        }
        /*施工单节点属性信息*/
        if(orderInfos.containsKey(OrderNodeDefineUtils.NODE_ITEM) && orderInfos.getJSONArray(OrderNodeDefineUtils.NODE_ITEM).size()>0){
            JSONArray nodes = orderInfos.getJSONArray(OrderNodeDefineUtils.NODE_ITEM);
            for(int i=0;i<nodes.size();i++){
                JSONObject node = nodes.getJSONObject(i);
                workNodeAttrService.insert(node);
            }
        }
        /*订单客户信息*/
        if(orderInfos.containsKey(OrderNodeDefineUtils.ORDER_CUSTOMER) && orderInfos.getJSONObject(OrderNodeDefineUtils.ORDER_CUSTOMER).size()>0){
            JSONObject order = orderInfos.getJSONObject(OrderNodeDefineUtils.ORDER_CUSTOMER);
            orderCustomerService.insert(order);
        }
        /*检查用户信息*/
        if(orderInfos.containsKey(OrderNodeDefineUtils.USER_INFO) && orderInfos.getJSONObject(OrderNodeDefineUtils.USER_INFO).size()>0){
            JSONObject user = orderInfos.getJSONObject(OrderNodeDefineUtils.USER_INFO);
            user = userService.addUser(user);
        }
        /*发送用户邮件信息*/
        if(orderInfos.containsKey(OrderNodeDefineUtils.USER_EMAIL) && orderInfos.getJSONObject(OrderNodeDefineUtils.USER_EMAIL).size()>0){
            JSONObject email = orderInfos.getJSONObject(OrderNodeDefineUtils.USER_EMAIL);
          JSONObject mailResult =  mailService.insertEmail(email);
            if(mailResult.containsKey("msgCode") && "9".equals(mailResult.getString("msgCode"))){
                throw new UserException(ResultEnum.UNKONE_ERROR.getCode(),"发送邮件失败!");
            }
        }
      /*------------------------接口数据-------------------------*/
        if(orderInfos.containsKey(OrderNodeDefineUtils.ACCT_SYNC_FEE) && orderInfos.getJSONArray(OrderNodeDefineUtils.ACCT_SYNC_FEE).size()>0){
            JSONArray nodes = orderInfos.getJSONArray(OrderNodeDefineUtils.ACCT_SYNC_FEE);
            for(int i=0;i<nodes.size();i++){
                JSONObject node = nodes.getJSONObject(i);
                acctFeeSyncInterface.acctFeeSync(node);
            }
        }

    }
    @Transactional
    public void stateInfoUpdate(JSONObject json){
        if(json == null){
            throw new UserException(ResultEnum.ORDER_INFO_ERROR);
        }
        if(json.containsKey("orderId")){
            /*订单*/
            Order order = new Order();
            order.setOrderId(json.getLong("orderId"));
            order.setOrderState(String.valueOf(Constant.ORDER_STATE_DOING));
            orderService.updateOrderState(order);
            /*工单状态更新*/
            Work work = new Work();
            work.setOrderId(json.getLong("orderId"));
            work.setWorkState(Constant.WORK_STATE_DOING);
            workService.updateWorkState(work);
        }else{
            throw new UserException(ResultEnum.PARAM_ERROR);
        }
    }
    
    public JSONObject callBackWorkAttr(JSONObject jsonObject) {
		//Long workId = jsonObject.getLong("workId");
		//Long nodeId = jsonObject.getLong("nodeId");
		JSONObject workItems = jsonObject.getJSONObject(OrderNodeDefineUtils.WORK_ITEM);
		//node_item_callback{nodeAccount,nodeAcctPwd,applianceName}
        JSONArray nodeItems = new JSONArray();
        /*1、节点回填信息*/
        workNodeAttrService.nodeItemInfos(workItems,jsonObject,nodeItems,"node_item_callback");
        for(int i=0;i<nodeItems.size();i++){
            JSONObject node = nodeItems.getJSONObject(i);
            workNodeAttrService.insert(node);
        }
        /*2、客户回填信息*/
        JSONArray custItems = new JSONArray();
        //获取客户id
        if(!jsonObject.containsKey("custId")) throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"客户ID{custId}不存在！");
        Long custId = jsonObject.getLong("custId");
        /*同一个客户多次调用，以第一个准*/
        orderAttrService.geneAttrInfosCondition(workItems,custId,Constant.ATTR_TYPE_CUST,custItems,"item_cust_callback");
        for(int i=0;i<custItems.size();i++){
            JSONObject node = custItems.getJSONObject(i);
            orderAttrService.insert(node);
        }
        /*3、工单属性回填信息*/
        /*4、订单属性回填信息*/
        /*5、产品回填信息*/
		return new JSONObject();
	}
    
	@Transactional
	public JSONObject completeWork(JSONObject json) {
		Long workId = json.getLong("workId");
		Long userId = json.getLong("userID");
		callBackWorkAttr(json);
		JSONObject workItems = json.getJSONObject(OrderNodeDefineUtils.WORK_ITEM);
		//获取施工单信息
		Work work = workService.getWorkInfo(workId);
		if(work == null) throw new UserException("3001","不存在该工单信息:workId="+workId);
		if(!workItems.containsKey("finishTime") || workItems.getDate("finishTime")==null){
			throw new UserException("传入时间格式不对！"+workItems.getString("finishTime"));
		}
		work.setWorkState(Constant.WORK_STATE_DONE);
		work.setFinishTime((workItems.containsKey("finishTime")&&workItems.getDate("finishTime")!=null)?workItems.getDate("finishTime"):new Date());
		work.setConstructUser(userId);
		workService.updateWork(work);
		
		JSONObject orderItemJson = new JSONObject();
		orderItemJson.put("finishTime", workItems.containsKey("finishTime")?workItems.getString("finishTime"):DateUtils.getDate());
		json.put("orderId", work.getOrderId());
		json.put(OrderNodeDefineUtils.ORDER_ITEM, orderItemJson);
		JSONObject finishJson = completeOrder(json);
		return finishJson;
	}
	
	public JSONObject completeOrder(JSONObject json) {
		Long orderId = json.getLong("orderId");
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("orderFinish", "0");
		// 判断是否工单都施工完成
		//List<Work> allWorks = workService.getWorksByOrderId(orderId);
		//List<Work> doneWorks = workService.getWorksByOrderIdAndState(orderId,Constant.WORK_STATE_DONE);
        int count = workService.getNotWorkStateCount(orderId);
		if(count==0){
			// 记录施工完成时间
			recordOrderBackItem(json);
			//触发订单完工接口
			jsonObject = finishService.finishOrder(orderId);
			jsonObject.put("orderFinish", "1");
		}
        return jsonObject;
		/*else {
			throw new UserException("存在未施工完成工单！不能发起订单竣工");
		}*/
	}
	private void recordOrderBackItem(JSONObject json) {
		Long orderId = json.getLong("orderId");
		JSONObject orderItem = json.getJSONObject(OrderNodeDefineUtils.ORDER_ITEM);
		for (Map.Entry<String, Object> entry : orderItem.entrySet()) {
			JSONObject attr = new JSONObject();
			attr.put("id",orderId);
			attr.put("modifyTag",Constant.ADD);
			attr.put("attrType",Constant.ATTR_TYPE_ORDER);
			attr.put("attrCode", entry.getKey());
			attr.put("attrValue", entry.getValue());
			attr.put("beginDate",new Date());
			attr.put("endDate",DateUtils.parseDate(Constant.END_DATE));
			orderAttrService.insert(attr);
			if("finishTime".equals(entry.getKey())){
				Date finishTime = DateUtils.parseDate(entry.getValue());
				//更新订单下所有套餐时间
				List<OrderDiscnt> orderDiscnts = orderDiscntService.getByOrderId(orderId);
				for (OrderDiscnt orderDiscnt : orderDiscnts) {
					//获取资费属性（时长和单位）
					OrderDiscntFee discntFee = orderDiscntFeeService.getByDiscntInstIdAndOrderId(orderDiscnt.getDiscntInstId(),orderId);
					Integer timeLength = discntFee.getBillingCycle();
					String unit = discntFee.getCycleUnit();
					if(Constant.ADD.equals(orderDiscnt.getModifyTag())){
						orderDiscnt.setBeginDate(finishTime);
						System.out.println(entry.getValue().toString()+"----" +timeLength+"----" + unit);
						orderDiscnt.setEndDate(DateUtils.getEndTime(entry.getValue().toString(), timeLength, unit));
					}else if (Constant.DEL.equals(orderDiscnt.getModifyTag())) {
						orderDiscnt.setEndDate(new Date(finishTime.getTime()-1000));
					}
					orderDiscntService.updateByInstId(orderDiscnt);
				}
			}
		}
		
	}
    @Transactional
    public JSONObject completeNodeLogistics(JSONObject json) {
        Long workId = json.getLong("workId");
        Long nodeId = json.getLong("nodeId");
        Work work = workService.getWorkInfo(workId);
        if(Constant.WORK_STATE_DONE==work.getWorkState()){
            work.setWorkState(Constant.WORK_STATE_LOGISTICS);
            logger.debug("工单更新信息="+JSON.toJSONString(work));
            workService.updateWorkState(work.getWorkId(),work.getWorkState());
        }
        /*记录物流信息*/
        Logistics logistics = JSON.parseObject(json.toJSONString(),Logistics.class);
        logistics.setNodeId(work.getNodeId());
        logisticsServer.insertLogistics(logistics);


        //messageBox
        /*发送通知邮件，获取发送邮件的字段信息，产品，节点，客户*/
        JSONObject content = logisticsServer.getLogisticsMailInfo(workId,nodeId);
        content.put("company",logistics.getCompany());
        content.put("outLogisticsId",logistics.getOutLogisticsId());
        /*查询发送盒子的客户用户列表*/
        logger.info("custId="+content.getLong("custId"));
        JSONArray boxUsers = custUserService.getUserIdByCustId(content.getLong("custId"));
        logger.debug("消息通知人员列表："+boxUsers.toJSONString());
        List<Long> users = boxUsers.stream().map(o -> ((JSONObject)o).getLong("userId")).collect(Collectors.toList());
        logger.info("消息通知人员列表2："+JSON.toJSONString(users));
        users.add( json.getLong("userID"));
        /*存储消息盒子*/
        JSONObject msgBox = new JSONObject();
        msgBox.put("msgType", MessageBoxEnum.WORK_MSG.getType());
        msgBox.put("msgName", MessageBoxEnum.WORK_MSG.getName());
        String tagInfo = tagService.getTagInfoOne(Constant.MSG_POST_TYPE).getString("tagInfo");
        msgBox.put("msgContent", MsgBoxUtil.geneBoxMessage(tagInfo,content));
        msgBoxServer.insertMsgAndUserInfo(msgBox,users);
        /*处理邮件*/
        JSONObject email = new JSONObject();
        email.put("sysCode", "CRM");
        email.put("msgTo", content.getString("contactEmail"));
        email.put("subject", "邮寄信息通知");
        email.put("bcc","shiq@btte.net");
        email.put("content", content);
        email.put("templateName", Constant.MAIL_POST_TEMP);
        email.put("msgType", "1");
        JSONObject mailResult = mailService.insertEmail(email);
        if(mailResult.containsKey("msgCode") && "9".equals(mailResult.getString("msgCode"))){
            throw new UserException(ResultEnum.UNKONE_ERROR.getCode(),"发送邮件失败！workId="+workId);
        }
        return null;
    }
}
